package com.bycx.framework.redis;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import org.springframework.data.redis.core.DefaultTypedTuple;
import org.springframework.data.redis.core.ZSetOperations.TypedTuple;

import java.util.*;

public abstract class AbstractRedisDao{
    protected String toJson(Object obj) {
        return JSON.toJSONString(obj, SerializerFeature.SortField);
    }
 
    protected <T> T parseJson(String json, Class<T> clazz) {
        return JSON.parseObject(json, clazz);
    }
 
    protected List<String> toJsonList(Collection<?> values) {
        if (values == null) {
            return null;
        }
 
        List<String> result = new ArrayList<String>();
        for (Object obj : values) {
            result.add(toJson(obj));
        }
        return result;
    }
     
    protected <T> List<T> parseJsonList(List<String> list, Class<T> clazz) {
        if (list == null) {
            return null;
        }
        List<T> result = new ArrayList<T>();
        for (String s : list) {
            result.add(parseJson(s, clazz));
        }
        return result;
    }
    
    protected List<String> setToList(Set<String> set) {
        if (set == null) {
            return null;
        }
        return new ArrayList<String>(set);
    }
    
    protected Set<TypedTuple<String>> toTupleSet(List<TypedTuple<?>> tupleList) {
        Set<TypedTuple<String>> tupleSet = new LinkedHashSet<TypedTuple<String>>();
        for (TypedTuple<?> t : tupleList) {
            tupleSet.add(new DefaultTypedTuple<String>(toJson(t.getValue()), t.getScore()));
        }
        return tupleSet;
    }
}
